package cn.itcast.bos.web.action.base;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFAnchor;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

import cn.itcast.bos.domain.base.Area;
import cn.itcast.bos.service.base.AreaService;

@ParentPackage("json-default")
@Namespace("/")
@Controller
@Scope("prototype")
public class AreaAction extends ActionSupport implements ModelDriven<Area> {

	public Area area = new Area();

	@Override
	public Area getModel() {
		// TODO Auto-generated method stub
		return area;
	}

	/// 获取File name默认是File
	private File file;

	public void setFile(File file) {
		this.file = file;
	}

	// 注入Service
	@Autowired
	private AreaService areaService;

	@Action(value = "area_batchImport")
	public String saveBatch() throws IOException {
		// 定义集合
		List<Area> list = new ArrayList<Area>();
		// 基于HSSF 解析.Xls 文件
		// 加载文件
		HSSFWorkbook hssfworkbook = new HSSFWorkbook(new FileInputStream(file));
		// 加载sheet
		HSSFSheet sheet = hssfworkbook.getSheetAt(0);
		// 读取判断sheet 跳过第一行 和 空行
		for (Row row : sheet) {
			/// 跳过表头
			if (row.getRowNum() == 0) {
				continue;
			}
			// 跳过空行
			if (row.getCell(0) == null || StringUtils.isBlank(row.getCell(0).getStringCellValue())) {
				continue;
			}

			// 接受参数
			Area area = new Area();
			area.setId(row.getCell(0).getStringCellValue());
			area.setProvince(row.getCell(1).getStringCellValue());
			area.setCity(row.getCell(2).getStringCellValue());
			area.setPostcode(row.getCell(3).getStringCellValue());
			area.setDistrict(row.getCell(4).getStringCellValue());
			// 编码 基于PiNyin4j 进行编码
			String province = area.getProvince();
			String city = area.getCity();
			String district = area.getDistrict();
			province = province.substring(0, province.length() - 1);
			city = city.substring(0, city.length() - 1);
			district = district.substring(0, district.length() - 1);
			// String [] headArray =
			list.add(area);
		}
		// 调用业务层】
		areaService.saveBatch(list);

		return NONE;
	}

	// 属性驱动
	private int page;
	private int rows;

	public void setPage(int page) {
		this.page = page;
	}

	public void setRows(int rows) {
		this.rows = rows;
	}

	// 根据条件查询
	@Action(value = "area_pageQuery", results = { @Result(name = "success", type = "json") })
	public String setQuery() {
		// 构造分页 查询对象
		Pageable pageable = new PageRequest(page - 1, rows);
		/*
		 * 构造条件查询方法， 如果方法返回null 代表无条件查询 Root 参数，获取条件表达式 name=? age=?
		 * CriteriaQuery 参数， 构造简单条件查询返回， 提供where 方法 CriterriaBuilder 参数
		 * 构造Predicate 对象， 条件对象 ，构造复杂查询效果
		 */

		Specification<Area> specification = new Specification<Area>() {

			@Override
			public Predicate toPredicate(Root<Area> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> list = new ArrayList<Predicate>();
				// root:当前查询root跟对象 Courier
				// 添加条件
				// 根据省份模糊查询
				if (StringUtils.isNoneBlank(area.getProvince())) {
					// 进行查询
					Predicate p1 = cb.like(root.get("province").as(String.class), "%" + area.getProvince() + "%");
					list.add(p1);
				}
				if (StringUtils.isNoneBlank(area.getCity())) {
					Predicate p2 = cb.like(root.get("city").as(String.class), "%" + area.getCity() + "%");
					list.add(p2);

				}
				if (StringUtils.isNoneBlank(area.getDistrict())) {

					Predicate p3 = cb.like(root.get("district").as(String.class), "%" + area.getDistrict() + "%");
					list.add(p3);

				}
				/// 将集合进行转换 转换 成数组 进行 保存
				return cb.and(list.toArray(new Predicate[0]));
			}
		};
		// 调用业务层完成查询
		Page<Area> pageDate = areaService.findQuery(specification, pageable);
//根据查询结果  根据 dategary 类型进行数据封装
		Map<String, Object> request = new HashMap<String, Object>();
		request.put("total", pageDate.getTotalElements());
		request.put("rows", pageDate.getContent());
		// 将Map转换成JsoN
		ActionContext.getContext().getValueStack().push(request);

		return SUCCESS;
	}

}
